package com.example.service.impl;

import com.example.config.ClientConfig;
import com.example.model.bo.Record;
import com.example.service.DataOwnService;
import com.example.utils.ContractAddressManager;
import com.example.utils.PropertyUtil;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.transaction.manager.AssembleTransactionProcessor;
import org.fisco.bcos.sdk.transaction.manager.TransactionProcessorFactory;
import org.fisco.bcos.sdk.transaction.model.dto.CallResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DataOwnServiceImpl implements DataOwnService {


    public static final String TraceToTheSourceABI = com.example.utils.IOUtil.readResourceAsString("abi/TraceToTheSource.abi");
    private final String TraceToTheSourceAddress = ContractAddressManager.getAddressFromContractNote("TraceToTheSource");


    @Autowired
    private Client client;

    AssembleTransactionProcessor txProcessor;

    @Override
    public List<Record> getOwnData() throws Exception {
        //登录信息
        String userName = PropertyUtil.getUserName();
        AccountManager.loadP12Account(client, ClientConfig.account_keyfile_path + userName, ClientConfig.account_password);
        this.txProcessor = TransactionProcessorFactory.createAssembleTransactionProcessor(this.client, this.client.getCryptoSuite().getCryptoKeyPair());
        //智能合约对应的参数列表
        List<Object> args = new ArrayList<>();
        CallResponse getRecordByUser = this.txProcessor.sendCall(this.client.getCryptoSuite().getCryptoKeyPair().getAddress(), TraceToTheSourceAddress, TraceToTheSourceABI, "getRecordsBySender", args);
        //获取智能合约函数返回值
        List<List<Object>> records = (List<List<Object>>) getRecordByUser.getReturnObject().get(0);
        List<Record> Records = new ArrayList<>();
        int id = 1;
        //将返回值进行封装
        for (List<Object> record : records) {
            String senderUserName = (String) record.get(2);
            String receiverUserName = (String) record.get(3);
//            log.info("get...5...:{}", record.get(5));
            ArrayList<BigInteger> hashKey = (ArrayList<BigInteger>) record.get(5);
            String cid = (String) record.get(7);
            String fileName = (String) record.get(8);
            String timeStamp = (String)record.get(9);
            Record recordItem = new Record(id++, senderUserName, receiverUserName, hashKey, cid, fileName, timeStamp, null);
           // System.out.println(recordItem);
            Records.add(recordItem);
        }
//        System.out.println("fuck的hashkey：" + Arrays.toString(Records.get(Records.size() - 1).getHashKey().toArray(new BigInteger[0])));
        return Records;
    }

}
